/**
 * 单位树组件
 */

import styled from '@emotion/styled';
import { TreeSelect, TreeSelectProps } from 'antd';
import { useEffect, useState } from 'react';
import { useRecoilState } from 'recoil';

import { userState } from '../../stores/user';
import { request } from '../../utils/request';
import { SysUnitTree, useGetUnitTree } from '../../service/unit-service';

interface IUnitTreeProps {
    getCheckUnit: (unitId: string, unitName: string) => void;
    checkedUnitd?: string;
    initUnitName: string | undefined;
}

interface DataNode {
    title: string;
    value: string;
    isLeaf: boolean;
    children?: DataNode[];
}

export const UnitTreeSelect = ({ getCheckUnit, checkedUnitd, initUnitName }: IUnitTreeProps) => {
    const [user] = useRecoilState(userState);
    const [queryParams] = useState<{ unitId: string }>({
        unitId: user.userInfo.unitId || '',
    });
    const { data: dataSource } = useGetUnitTree(queryParams);
    const [treeData, setTreeData] = useState<DataNode[]>();

    useEffect(() => {
        if (dataSource) {
            const data: DataNode[] = [
                {
                    title: dataSource.unitName,
                    value: dataSource.unitId,
                    isLeaf: dataSource.isParent === 1 ? false : true,
                },
            ];
            const children: DataNode[] = [];
            if (dataSource.children && dataSource.children.length > 0) {
                dataSource.children.forEach((ele) => {
                    children.push({
                        title: ele.unitName,
                        value: ele.unitId,
                        isLeaf: ele.isParent === 1 ? false : true,
                    });
                });
            }
            data[0].children = children;
            setTreeData(data);
        }
    }, [dataSource]);

    /**点击单位的回调 */
    const onChange = (selectedKeys: string, labelList: React.ReactNode[]) => {
        const unitId = selectedKeys;
        getCheckUnit(unitId, labelList[0] as string);
    };

    /**点击加载子单位回调 */
    const onLoadData: TreeSelectProps['loadData'] = async ({ key }) => {
        if (key !== user.userInfo.unitId) {
            const res = await request<SysUnitTree>('/unit/getUnitTreeById', {
                data: { unitId: key },
                token: user?.token || '',
            });
            setTreeData((origin) => updateTreeData(origin || [], key as string, res));
        } else {
            return new Promise<void>((resolve) => {
                resolve();
                return;
            });
        }
    };

    /**跟换后台数据生成树对象的数据 */
    const genTreeData = (res: SysUnitTree) => {
        return res.children.map((e) => {
            return {
                title: e.unitName,
                value: e.unitId,
                isLeaf: e.isParent === 1 ? false : true,
            };
        });
    };
    /**更新树对象 */
    const updateTreeData = (origin: DataNode[], key: string | number, res: SysUnitTree): DataNode[] => {
        return origin?.map((e) => {
            if (e.value === key) {
                return {
                    ...e,
                    children: genTreeData(res),
                };
            }
            if (e.children) {
                return {
                    ...e,
                    children: updateTreeData(e.children || [], key, res),
                };
            }
            return e;
        });
    };

    return (
        <UnitTreeContainer>
            <TreeSelect
                showSearch
                style={{ width: '100%' }}
                value={checkedUnitd}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder={initUnitName ? initUnitName : "选择单位"}
                allowClear
                loadData={onLoadData}
                onChange={onChange}
                treeData={treeData}
            />
        </UnitTreeContainer>
    );
};

export default UnitTreeSelect;

const UnitTreeContainer = styled.div``;
